package com.alibaba.cirtus.ots.application.app.ability.facade.v2serviceimpl;

import com.alibaba.citrus.ots.sales.plan.model.enums.StatPoolTypeEnum;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.epoch.app.bcorder.model.dto.BatchSubmitTaskRequest;
import com.epoch.app.bcorder.model.dto.BatchSubmitTaskResponse;
import com.epoch.app.bcorder.model.dto.EmployeeGetCurrentLoginResponse;
import com.epoch.app.bcorder.model.dto.PageQueryPlanScItemListRequest;
import com.epoch.app.bcorder.model.dto.PageQueryPlanScItemListResponse;
import com.epoch.app.bcorder.model.dto.PageQuerySalePlanListRequest;
import com.epoch.app.bcorder.model.dto.PageQuerySalePlanListResponse;
import com.epoch.app.bcorder.model.dto.SubTotalSalesPlanSCItemRequest;
import com.epoch.app.bcorder.model.dto.SubTotalSalesPlanSCItemResponse;
import com.epoch.app.bcorder.service.BcOrderService;
import com.epoch.app.bcorder.service.SalesPlanService;
import com.epoch.app.otsapplicationappsdk.channellistpage.dto.AsyncRequest;
import com.epoch.app.otsapplicationappsdk.channellistpage.dto.RenderRequest;
import com.epoch.app.otsapplicationappsdk.channellistpage.dto.SubmitRequest;
import com.epoch.app.otsapplicationappsdk.channellistpage.service.ChannelListPageService;
import lombok.Data;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class ChannelListPageV2ServiceImpl implements ChannelListPageService {

    private static Log log = Log.getLogger(ChannelListPageV2ServiceImpl.class);

//    @Autowired
//    private SalesPlanService salesPlanService;
    @Autowired
    private SalesPlanService salesPlanService;

//    @Autowired
//    private BcOtsService bcOtsService;
    @Autowired
    private BcOrderService bcOtsService;

    @Override
    public Object render(RenderRequest renderRequest) {
        log.info("渠道列表渲染页面请求参数 {} ", JSONObject.toJSONString(renderRequest));
        return create(renderRequest);
    }

    @Override
    public Object async(AsyncRequest asyncRequest) {
        log.info("渠道列表异步页面请求参数 {} ", JSONObject.toJSONString(asyncRequest));
        Object request = asyncRequest.getRequest();
        if (Objects.isNull(request)) {
            return null;
        }
        JSONObject result = new JSONObject();

        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(request));
        JSONObject fields = jsonObject.getJSONObject("fields");
        JSONObject fieldsJSONObject = fields.getJSONObject("fields");
        result.put("planId", fieldsJSONObject.getString("planId"));

        JSONObject updateFields = fields.getJSONObject("updateFields");
        result.put("activeTab", updateFields.getString("newActiveTab"));

        RenderRequest renderRequest = result.toJavaObject(RenderRequest.class);
        return create(renderRequest);
    }

    public Object create(RenderRequest renderRequest) {
        JSONObject result = new JSONObject();
        try {
            PageQuerySalePlanListRequest infoRequest = new PageQuerySalePlanListRequest();
            infoRequest.setId(renderRequest.getPlanId());
            try {
                PageQuerySalePlanListResponse infoResponse = salesPlanService.pageQuerySalePlanList(infoRequest);
                if (Objects.nonNull(infoResponse) && CollectionUtils.isNotEmpty(infoResponse.getResult())) {
                    result.put("infoResponse", infoResponse.getResult().get(0));
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("查询月度计划{}", e);
            }

            SubTotalSalesPlanSCItemRequest itemRequest = new SubTotalSalesPlanSCItemRequest();
            itemRequest.setPlanId(renderRequest.getPlanId());
            itemRequest.setPoolType(StatPoolTypeEnum.ORGANIZATION.getPoolType());
            try {
                SubTotalSalesPlanSCItemResponse itemResponse = salesPlanService.subTotalSalesPlanSCItem(itemRequest);
                result.put("itemResponse", itemResponse.getResult());
            } catch (Exception e) {
                e.printStackTrace();
                log.error("计算月度计划货品小计{}", e);
            }

            EmployeeGetCurrentLoginResponse employeeGetCurrentLoginResponse = bcOtsService.employeeGetCurrentLogin();
            if (employeeGetCurrentLoginResponse != null) {
                log.info("渠道列表页面 当前登录人API结果 {} ", JSONObject.toJSONString(employeeGetCurrentLoginResponse));
            }
            result.put("isSales", employeeGetCurrentLoginResponse.getIsSales());

            List childOrgList = new ArrayList();
            //String roleCodes = employeeGetCurrentLoginResponse.getRoleCodes();

            //1.查出最上级组织审批数据(与pc端数据一致)  2.逐级往下过滤，查出所有层级审批数据 3.奥创过滤是否是需要审批数据
            List list = getChildOrgList(null, null, null, renderRequest.getPlanId(), employeeGetCurrentLoginResponse.getIsSales());
            childOrgList.addAll(list);

            for (Object obj : list) {
                JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(obj));
                log.info("一级审批状态 {} , {} ",jsonObject.get("auditStatus"),jsonObject.getString("auditStatusName"));
                List childList = getChildOrgList(null, jsonObject.getString("bizId"), null, renderRequest.getPlanId(), employeeGetCurrentLoginResponse.getIsSales());
                if (CollectionUtils.isNotEmpty(childList)) {
                    childOrgList.addAll(childList);
                    for (Object obj1 : childList) {
                        JSONObject jsonObject1 = JSONObject.parseObject(JSON.toJSONString(obj1));
                        log.info("二级审批状态 {} , {} ",jsonObject1.get("auditStatus"),jsonObject1.getString("auditStatusName"));
                        List childList1 = getChildOrgList(null, jsonObject1.getString("bizId"), null, renderRequest.getPlanId(), employeeGetCurrentLoginResponse.getIsSales());
                        if (CollectionUtils.isNotEmpty(childList1)) {
                            childOrgList.addAll(childList1);
                            for (Object obj2 : childList1) {
                                JSONObject jsonObject2 = JSONObject.parseObject(JSON.toJSONString(obj2));
                                log.info("三级审批状态 {} , {} ",jsonObject2.get("auditStatus"),jsonObject2.getString("auditStatusName"));
                                List childList2 = getChildOrgList(null, jsonObject2.getString("bizId"), null, renderRequest.getPlanId(), employeeGetCurrentLoginResponse.getIsSales());
                                if (CollectionUtils.isNotEmpty(childList2)) {
                                    childOrgList.addAll(childList2);
                                    for (Object obj3 : childList2) {
                                        JSONObject jsonObject3 = JSONObject.parseObject(JSON.toJSONString(obj3));
                                        log.info("四级审批状态 {} , {} ",jsonObject3.get("auditStatus"),jsonObject3.getString("auditStatusName"));
                                        List childList3 = getChildOrgList(null, jsonObject3.getString("bizId"), null, renderRequest.getPlanId(), employeeGetCurrentLoginResponse.getIsSales());
                                        if (CollectionUtils.isNotEmpty(childList3)) {
                                            childOrgList.addAll(childList3);
                                            for (Object obj4 : childList3) {
                                                JSONObject jsonObject4 = JSONObject.parseObject(JSON.toJSONString(obj4));
                                                log.info("五级审批状态 {} , {} ",jsonObject4.get("auditStatus"),jsonObject4.getString("auditStatusName"));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }


//            if (null != roleCodes) {
//                if (roleCodes.contains(RoleCodeEnum.SALE_MAN.getCode())) {
//                    childOrgList = getChildOrgList(employeeGetCurrentLoginResponse.getEmployeeId(), null, SalesStatBizTypeEnum.SALESMAN.getOrganizationType(), renderRequest.getPlanId(), employeeGetCurrentLoginResponse.getIsSales());
//                } else if (roleCodes.contains(RoleCodeEnum.CHANNEL_MANAGER.getCode())) {
//                    List list = getChildOrgList(null, employeeGetCurrentLoginResponse.getRelatedOrganizationId(), null, renderRequest.getPlanId(), employeeGetCurrentLoginResponse.getIsSales());
//                    for (Object obj : list) {
//                        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(obj));
//                        List childList = getChildOrgList(null, jsonObject.getString("bizId"), null, renderRequest.getPlanId(), employeeGetCurrentLoginResponse.getIsSales());
//                        if (CollectionUtils.isNotEmpty(childList)) {
//                            childOrgList.addAll(childList);
//                        }
//                    }
//                    childOrgList.addAll(list);
//                } else if (roleCodes.contains(RoleCodeEnum.PLAN_DISPATCHER.getCode())) {
//                    List list = getChildOrgList(null, employeeGetCurrentLoginResponse.getRelatedOrganizationId(), null, renderRequest.getPlanId(), employeeGetCurrentLoginResponse.getIsSales());
//                    for (Object obj : list) {
//                        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(obj));
//                        List childList = getChildOrgList(null, jsonObject.getString("bizId"), null, renderRequest.getPlanId(), employeeGetCurrentLoginResponse.getIsSales());
//                        if (CollectionUtils.isNotEmpty(childList)) {
//                            childOrgList.addAll(childList);
//                        }
//                    }
//                } else if (roleCodes.contains(RoleCodeEnum.DEPARTMENT_MANAGER.getCode())) {
//                    List list = getChildOrgList(null, employeeGetCurrentLoginResponse.getRelatedOrganizationId(), null, renderRequest.getPlanId(), employeeGetCurrentLoginResponse.getIsSales());
//                    for (Object obj : list) {
//                        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(obj));
//                        List childList = getChildOrgList(null, employeeGetCurrentLoginResponse.getRelatedOrganizationId(), SalesStatBizTypeEnum.SALESMAN.getBizType(), renderRequest.getPlanId(), employeeGetCurrentLoginResponse.getIsSales());
//                        if (CollectionUtils.isNotEmpty(childList)) {
//                            childOrgList.addAll(childList);
//                        }
//                    }
//                } else if (roleCodes.contains(RoleCodeEnum.GENERAL_MANAGER.getCode())) {
//                    childOrgList = getChildOrgList(employeeGetCurrentLoginResponse.getRelatedOrganizationId(), null, SalesStatBizTypeEnum.BUSINESS_UNIT.getOrganizationType(), renderRequest.getPlanId(), employeeGetCurrentLoginResponse.getIsSales());
//                }
//
//            }

            result.put("listResponse", childOrgList);

            result.put("activeTab", renderRequest.getActiveTab());

            result.put("success", true);
            result.put("message", "");

        } catch (BeansException e) {
            result.put("success", false);
            result.put("message", "页面跑丢了");
        }
        return result;
    }

    @Override
    public Object submit(SubmitRequest submitRequest) {
        log.info("渠道列表提交页面请求参数 {} ", JSONObject.toJSONString(submitRequest));

        Object request = submitRequest.getRequest();
        if (Objects.isNull(request)) {
            return null;
        }
        JSONObject result = new JSONObject();

        JSONObject json = null;
        try {
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(request));
            JSONObject fields = jsonObject.getJSONObject("fields");
            result.put("modelId", fields.getString("planId"));
            result.put("model", 1);
            result.put("action", fields.getString("action"));
            if (null != fields.getString("remake")) {
                result.put("comment", fields.getString("remake"));
            }
            JSONArray bodyList = fields.getJSONArray("bodyList");
            List list = new ArrayList();
            for (Object obj : bodyList) {
                json = (JSONObject) JSONObject.toJSON(obj);
                if (json.getBoolean("isChecked")) {
                    Biz biz = new Biz();
                    biz.setBizId(json.getString("bizId"));
                    biz.setBizType(json.getInteger("bizType"));
                    list.add(biz);
                }
            }
            result.put("dimensionDTOList", list);
            BatchSubmitTaskRequest batchSubmitTaskRequest = result.toJavaObject(BatchSubmitTaskRequest.class);
            BatchSubmitTaskResponse batchSubmitTaskResponse = salesPlanService.batchSubmitTask(batchSubmitTaskRequest);

            json = new JSONObject();
            json.put("success", batchSubmitTaskResponse.getSuccess());
            json.put("message", "成功" + batchSubmitTaskResponse.getResult().getSucNum() + "个，" + "失败" + batchSubmitTaskResponse.getResult().getFailNum() + "个");
        } catch (Exception e) {
            json.put("success", false);
            json.put("message", "页面跑丢了");
        }
        return json;
    }

    private List getChildOrgList(String bizId, String parentId, Integer bizType, String planId, Boolean isSales) {
        PageQueryPlanScItemListRequest listRequest = new PageQueryPlanScItemListRequest();
        if (!isSales) {
            listRequest.setParentId(parentId);
        }
        listRequest.setPlanId(planId);
        listRequest.setBizType(bizType);
        listRequest.setBizId(bizId);
        listRequest.setPoolType(StatPoolTypeEnum.ORGANIZATION.getPoolType());

        PageQueryPlanScItemListResponse listResponse = salesPlanService.pageQueryPlanScItemList(listRequest);
        if (Objects.isNull(listResponse) || CollectionUtils.isEmpty(listResponse.getResult())) {
            return new ArrayList();
        }
        log.info("渠道列表渲染页面 查询计划货品API结果 {}", JSONObject.toJSONString(listResponse));
        return listResponse.getResult();
    }

    @Data
    public class Biz {
        private String bizId;
        private Integer bizType;
    }

}
